package com.zklh.leetcode.top100.problem207;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 课程表广度优先搜索算法实现
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/10/31
 */
public class Solution3 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] indeg = new int[numCourses];
        List<List<Integer>> edges = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            edges.add(new ArrayList<>());
        }

        for (int[] prerequisite : prerequisites) {
            edges.get(prerequisite[1]).add(prerequisite[0]);
            indeg[prerequisite[0]]++;
        }

        Queue<Integer> queue = new LinkedList<>();

        for (int i = 0; i < numCourses; i++) {
            if (indeg[i] == 0) {
                queue.add(i);
            }
        }

        int visited = 0;
        while (!queue.isEmpty()) {
            int course = queue.poll();
            visited++;
            List<Integer> edge = edges.get(course);
            for (Integer i : edge) {
                if (--indeg[i] == 0) {
                    queue.add(i);
                }
            }
        }

        return visited == numCourses;
    }

    public static void main(String[] args) {
        Solution3 solution3 = new Solution3();
/*        int numCourses = 2;
        int[][] prerequisites = {{1,0}};*/

/*        int numCourses = 4;
        int[][] prerequisites = {{0,1},{3,1},{1,3},{3,2}};*/

        int numCourses = 8;
        int[][] prerequisites = {{1, 0}, {2, 6}, {1, 7}, {6, 4}, {7, 0}, {0, 5}};
        System.out.println(solution3.canFinish(numCourses, prerequisites));
    }
}